<?php


class CallbackController extends CController
{
	
	public function actionIndex()
	{
		
		$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );

		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = WB_CALLBACK_URL;
			try {
				$token = $o->getAccessToken( 'code', $keys ) ;
			} catch (OAuthException $e) {
				
			}
		}
		
		if (!empty($token)) {
			$_SESSION['token'] = $token;
			setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
			
		
			if(!empty($_SESSION['token']['access_token'])){
				$c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
				//$c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_REQUEST['viewer'] );
				$ms  = $c->home_timeline(); // done
				$uid_get = $c->get_uid();
				$uid = $uid_get['uid'];
				$user_message = $c->show_user_by_id($uid);
				//var_dump($_SESSION);
				//var_dump($_REQUEST);
				//var_dump($user_message);
				//echo '<img src="'.$user_message['profile_image_url'].'" />';
				
				
				
					$model = new User;
					$user = $model->findByPk($user_message['id']);
					if(!empty($user)){
						if($user->token != $_SESSION['token']['access_token'] or $user->profile_image != $user_message['profile_image_url']){
							$user->token = $_SESSION['token']['access_token'];
							$user->profile_image = $user_message['profile_image_url'];
							$user->updatetime = time();
							$user->save();
						}
					
					}else{
						$model->id = $user_message['id'];
						$model->idstr = $user_message['idstr'];
						$model->screen_name = $user_message['screen_name'];
						$model->name = $user_message['name'];
						$model->profile_image = $user_message['profile_image_url'];
						$model->token = $_SESSION['token']['access_token'];
						$model->updatetime = time();
						
						$model->save();
						
						
					}
			}
			
			
			
		
			echo '授权完成,<a href="weibolist.php">进入你的微博列表页面</a><br />';

		} else {

			echo '授权失败。';

		}


	
	}

}


?>

